import os

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication
import sys

from ClientUi.controls.CustomList import CustomList, CustomListItemType
from ClientUi.deviceManager.deviceManagerBaseDlg import deviceManagerBaseDlg
from get_config import config, config_save
from ClientUi.deviceManager.dev_config import max_plc_num, global_plc_protocol

class plcSettingDlg(deviceManagerBaseDlg):
    def __init__(self):
        super().__init__()
        self.setWindowIcon(QIcon(f'{self._clientUiPath}\\images\\icon.ico'))  # 设置窗口图标
        self.setWindowTitle('PLC管理')
        plcList = self._getDevList()
        # 表格中控件绑定事件
        if plcList is not None:
            plcList.connectComboBox(1, self.__changeProtocolType)
            plcList.connectLineEdit(2, self.__changePlcIp)
            plcList.connectLineEdit(3, self.__changePlcPort)
            plcList.connectLineEdit(4, self.__changePlcName)
            plcList.connectButton(5, self.__clickConnectTest)
            plcList.connectButton(6, self.__clickClearInfo)

    def _onInitTopWidget(self):
        self._createTopWidget('PLC数量：', max_plc_num, config.get('used_plc_num', 0), True)

    def _onInitDevListHeader(self, devList: CustomList):
        devList.SetColumnTitleAndTypes((('序号', CustomListItemType.LABEL),
                                        ('协议类型', CustomListItemType.COMBOBOX),
                                        ('IP', CustomListItemType.EDIT),
                                        ('端口', CustomListItemType.EDIT),
                                        ('备注', CustomListItemType.EDIT),
                                        ('连接测试', CustomListItemType.BUTTON),
                                        ('清除', CustomListItemType.BUTTON)))
        devList.SetEditMaxLen(2, 15)
        devList.SetEditMaxLen(3, 5)
        devList.SetEditMaxLen(4, 10)

    def _onInitDevListRows(self, rowCount: int, devList: CustomList):
        devList.setRowCount(rowCount)
        for i in range(rowCount):
            devList.setRow(i, (f'{i + 1}', (global_plc_protocol, config.get(f'plc{i+1}_protocol', '')),
                               config.get(f'plc{i+1}_ipaddress', ''), config.get(f'plc{i+1}_port'),
                               config.get(f'plc{i+1}_name'), '连接测试',
                                         {'icon': f'{self._clientUiPath}\\images\\reset.png'}))

    def _onSave(self):
        config['used_plc_num'] = self._getCurrentDevNum()
        for i in range(config['used_plc_num']):
            result = self.__getRowInfo(i)
            print(result)
            config[f"plc{i+1}_protocol"] = result[1]
            config[f"plc{i+1}_ipaddress"] = result[2]
            config[f"plc{i+1}_port"] = result[3]
            config[f"plc{i + 1}_name"] = result[4]

        config_save()
        self.accept()

    def __getRowInfo(self, rowIndex: int):
        return self._getDevList().getRow(rowIndex)

    def __clickConnectTest(self, row: int, column: int):
        print(f'__clickConnectTest: {row} {column}')
        result = self.__getRowInfo(row)
        print(result)
        ip = result[2]
        port = result[3]
        print(f'plc: {ip}:{port}')
        # Todo: 添加plc连接测试代码

    def __clickClearInfo(self, row: int, column: int):
        print(f'__clickClearInfo: {row} {column}')
        self._getDevList().clearRow(row, [CustomListItemType.EDIT, CustomListItemType.COMBOBOX])

    def __changeProtocolType(self, row: int, column: int, index: int):
        print(f'__changeProtocolType: {row} {column}, {index}')

    def __changePlcIp(self, row: int, column: int, ip: str):
        print(f'__changePlcIp: {row} {column}, {ip}')

    def __changePlcPort(self, row: int, column: int, port: str):
        print(f'__changePlcPort: {row} {column}, {port}')

    def __changePlcName(self, row: int, column: int, name: str):
        print(f'__changePlcName: {row} {column}, {name}')


def test_plcSettingDlg():
    app = QApplication(sys.argv)
    current_path = os.path.abspath(__file__)
    path = os.path.dirname(current_path)
    path = os.path.dirname(path)
    app.setStyleSheet(open(f'{path}/styleSheet.qss', encoding='utf-8').read())
    window = plcSettingDlg()
    window.showNormal()
    sys.exit(app.exec_())

if __name__ == '__main__':
    test_plcSettingDlg()